<?php

namespace App\Admin\Exceptions;

use App\Admin\Traits\ReponseJson;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

/**
 * Class ValidationException
 * @package App\Exceptions
 */
class ValidationException extends Exception
{
    /**
     * 所以驗證器相關的驗證異常
     */
    use ReponseJson;

    public function __construct(Validator $validator, $message = '', $code = 500, $jump = '')
    {
        $this->validator = $validator;
        $this->code      = $code;
        $this->message   = $message ?: $this->validator->errors()->all()[0];
        $this->jump      = $jump ?: request()->server('HTTP_REFERER') ?? '';
    }

    public function render(Request $request)
    {
        if ($request->expectsJson()) {
            return $this->failure(
                $this->message,
                $this->validator->errors()->all(),
                $this->code,
                $this->jump
            );
        }
        return view('admin.public.exception', [
            'code'    => $this->code,
            'message' => $this->validator->errors()->first(),
            'jump'    => $this->jump,
        ]);
    }
}
